package com.whj.servicessepush.controller;

import com.whj.internalcommon.request.PushRequest;
import com.whj.internalcommon.utils.SsmPrefixUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: wanghaijun
 * @Date: 2023/2/23 - 02 - 23 - 15:08 
 * @Description: com.whj.ssedriverclientweb.controller
 */

@RestController
@Slf4j
public class SseController {

    public static Map<String, SseEmitter> sseEmitterMap = new HashMap<>();

    /**
     * 建立连接
     *
     * @param userId 建立连接的id
     * @param identity 身份类型
     * @return
     */
    @GetMapping("/connect")
    public SseEmitter connect(@RequestParam Long userId, @RequestParam String identity) {
        log.info("用户的Id = " + userId, ",身份类型是：" + identity);
        SseEmitter sseEmitter = new SseEmitter(0l);
        String sseMapKey = SsmPrefixUtils.generatorSseKey(userId, identity);
        //将收到的消息存放到静态的map中
        sseEmitterMap.put(sseMapKey, sseEmitter);
        return sseEmitter;
    }
    /**
     *     发送连接
     * @param pushRequest userId 连接的用户  identity 身份类型  content  消息的类容
     * @return
     */
    @PostMapping("/push")
    public String push(@RequestBody PushRequest pushRequest) {
        Long userId = pushRequest.getUserId();
        String identity = pushRequest.getIdentity();
        String content = pushRequest.getContent();
        log.info("用户ID："+userId+",身份："+identity);
        String sseMapKey = SsmPrefixUtils.generatorSseKey(userId, identity);
        try {
            if (sseEmitterMap.containsKey(sseMapKey)) {
                sseEmitterMap.get(sseMapKey).send(content);
            } else {
                return "推送失败";
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "给用户：" + sseMapKey + "发送了消息:" + content;
    }

    /**
     * 移除sseEmitterMap发来的值 关闭连接
     *
     * @param userId 关闭连接的用户
     * @param identity 身份类型
     * @return
     */
    @GetMapping("/close")
    public String close(@RequestParam Long userId, @RequestParam String identity) {
        String sseMapKey = SsmPrefixUtils.generatorSseKey(userId, identity);
        log.info("关闭连接：" + sseMapKey);
        if (sseEmitterMap.containsKey(sseMapKey)) {
            sseEmitterMap.remove(sseMapKey);
        }
        return "close 成功！";
    }
}
